//app.js
var com = require("./utils/common.js");
var util = require("./utils/util.js");
var more = 0;
var socketState;
App({
  onLaunch: function () {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.systemInfo = res;
      }
    })
    that.checkVersion();
    that.wxLogin();
  },

  //微信登陆
  wxLogin() {
    var that = this;
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId
        that.getOpenid(res.code);
      }
    })
    wx.onNetworkStatusChange(function (res) {
      if (res.networkType == 'none') {
        that.showToast('网络连接断开');
      }
    })
  },
  // 扫码
  scanning: function (success) {
    var that = this;
    wx.scanCode({
      success: (res) => {
        console.log(res)
        var values = '';
        if (res.result.indexOf('device_no=') > -1) { //设备码
          var strs = res.result.split('?device_no=');
          values = strs[1];
        } else { //主板码
          var code = res.result.split(';')
          if (!util.isExitsVariable(code) || code.length == 0) {
            that.showToast('扫码失败');
            return false;
          }
          if (code[2] && code[2].indexOf(":") != -1) {
            var val = code[2].split(':');
            if (!util.isExitsVariable(val) || val.length == 0) {
              that.showToast('扫码失败');
              return false;
            }
            values = val[1];
          } else {
            values = code[0];
          }
        }
        success(values);

      },
      fail: (res) => {
        that.showToast('扫码失败，请重试！');
      }
    })
  },
  //检查版本
  checkVersion() {
    var that = this;
    const version = wx.getSystemInfoSync().SDKVersion
    console.log(version, "version")
    if (that.compareVersion(version, '1.6.8') < 0) {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用部分功能，请升级到最新微信版本后重试。'
      })
      return false;
    }
    return true;
  },
  compareVersion(v1, v2) {
    v1 = v1.split('.')
    v2 = v2.split('.')
    const len = Math.max(v1.length, v2.length)

    while (v1.length < len) {
      v1.push('0')
    }
    while (v2.length < len) {
      v2.push('0')
    }
    for (let i = 0; i < len; i++) {
      const num1 = parseInt(v1[i])
      const num2 = parseInt(v2[i])

      if (num1 > num2) {
        return 1
      } else if (num1 < num2) {
        return -1
      }
    }

    return 0
  },

  //字体下载
  loadFontfun() {
    var that = this;
    console.log('调用了');
    wx.loadFontFace({
      family: 'huawen',
      source: 'url("' + that.globalData._network_path + 'censcbk.ttf")',
      success: function (res) {
        console.log('>>>>', res);
      },
      fail: function (res) {
        more += 1;
        if (more >= 5) {
          return false;
        }
        that.loadFontfun();//再次调用字体
      }
    })
  },

  //发起网络请求,获取openid,session_key
  getOpenid: function (code) {
    var that = this;
    that.ajax({
      url: 'Engineer/Wx/register',
      data: { code: code},
      success: function (res) {
        if (res.data.code == 1000) {
          wx.setStorageSync('openid', res.data.data.openid);
        } else if (res.data.code == -1000) {
          that.wxLogin();//重新调取微信登录
        }else{
          that.showToast(res.data.message);
        }
      }
    })
  },
  //跳转到登陆页面
  redirectLogin($msg='') {
    console.log('1111111111');
    if(!util.isExitsVariable($msg)){
      $msg = '您还未登录，请先登录';
    }
    var that = this;
    //避免重复登录
    var is_login = wx.getStorageSync('is_login');
    console.log('2222222', is_login);
    if (is_login) {
      return false;
    }
    console.log('2222222', is_login);

    wx.setStorageSync('is_login', true);
    that.showModal("", $msg, function () {
      wx.navigateTo({
        url: '/pages/myCenter/login/login',
      })
    },function(){
      wx.setStorageSync('is_login', false);
    });
  },
  //获取登陆状态
  loginStatus(success, fail) {
    var that = this;
    //返回Promise对象
    return new Promise(
      function (resolve) {
        var token = wx.getStorageSync('token');
        var openid = wx.getStorageSync('openid');
        wx.request({
          method: "POST",
          url: that.globalData._url + 'Engineer/Engineers/loginStatus',
          header: {
            'token': token,// 默认值
            'openid': openid
          },
          success: (resolve) => {
            if (resolve.data.code == 1000) {
              success(resolve);
            } else if (resolve.data.code == -1006) {
              that.showModal("", resolve.data.message, function () {
                wx.navigateTo({
                  url: '/pages/myCenter/login/login',
                })
              });
            } else {
              fail(resolve);
            }

          }, error: (resolve) => {
            fail(resolve);
          }
        })
      })
  },
  //保存formId
  saveFormId: function(formId){
    console.log('****formId*****');
    var that = this;
    console.log(formId);
    var openid = wx.getStorageSync('openid');
    that.ajax({
      url: 'Common/Wx/saveFormId',
      data: { openid: openid, formId: formId },
      success: function (res) {
        console.log(res);
        if (res.data.code == 1000) {
          console.log('保存formId成功');
        } else {
          console.log('保存formId失败')
        }

      }
    })
  },
  // 修改工程人员位置
  updateLatlng: function (lat, lng) {
    var that = this;
    that.ajax({
      url: 'Engineer/Engineers/engineersEditInfo',
      method: 'POST',
      data: {
        lat: lat,
        lng: lng
      },
      success: function (res) {
        if (res.data.code == 1000) {
          console.log('修改成功')
        }
      }
    })
  },
  //websocket
  webSocket(){
    var account = wx.getStorageSync("account");
    var that = this;
    if(!util.isExitsVariable(account)){
        return false;
    }
    //创建一个 WebSocket 连接
    wx.connectSocket({
      url: that.globalData._socket_url,
      success:function(res){
        console.log(res)
      }
    })
    //
    wx.onSocketOpen(function(res){
      var arr = {};
      var that = this;
      var account = wx.getStorageSync("account");
      arr.controller_name = "Websocket";
      arr.method_name = "login_state";
      arr.data = account;
      var data = JSON.stringify(arr);
      wx.sendSocketMessage({
        data:data,
        success:function(res){
          console.log("发送",res);
        }
      })
      socketState = setInterval(function () {
        var data = {};
        data.controller_name = "Websocket",
          data.method_name = "ping";
        data.data = account;
        data = JSON.stringify(data);
        wx.sendSocketMessage({
          data: data,
        })
      }, 20000);
    })
    wx.onSocketMessage(function(res){
      var data = JSON.parse(res.data);
      console.log("接收消息", data)
    })
    wx.onSocketClose(function(res){
      console.log("关闭连接",res)
      // var login_time = wx.getStorageSync("login_time");
      // var time = new Date().getTime() - login_time;
      // clearInterval(socketState);
      // // if (time > 3600000) {
      //   console.log("请退出登陆")
      //   wx.removeStorageSync("account");
      //   wx.setStorageSync('isLogout', 1);
      //   wx.removeStorageSync('token');
        // wx.showModal({
        //   title: '',
        //   content: "该账号在其他设备登陆,若不是本人操作，建议及时修改密码",
        //   showCancel: false,
        //   success: function (res) {
        //     wx.navigateTo({
        //       url: '/pages/myCenter/login/login',
        //     })
        //   }
        // })
      //}
    })

  },
  //socket心跳
  socketPing(){
    console.log("sdssssss")
    socketState = setInterval(function () {
      var data = {};
      data.controller_name = "Websocket",
        data.method_name = "ping";
      data.data = account;
      data = JSON.stringify(data);
      wx.sendSocketMessage({
        data: data,
      })
    }, 20000);
  },
  //ajax 请求
  ajax(model) {
    var that = this;
    if (util.isExitsVariable(model.load)) {
      var msg = "加载中";
      if (util.isExitsVariable(model.msg)) {
        msg = model.msg;
      }
      wx.showLoading({
        title: msg,
      })
    }
    if (!util.isExitsVariable(model.method)) {
      model.method = "POST";
    }

    // 判断请求哪个接口
    if (model.url_type == 1) {
      //拼接url
      if (model.url.indexOf("https://") == -1 && model.url.indexOf("http://") == -1) {
        model.url = this.globalData.boss_url + model.url;
      }
    } else if(model.url_type == 2) {
      //拼接url
      if (model.url.indexOf("https://") == -1 && model.url.indexOf("http://") == -1) {
        model.url = this.globalData.crm_url + model.url;
      }
    } else {
      //拼接url
      if (model.url.indexOf("https://") == -1 && model.url.indexOf("http://") == -1) {
        model.url = this.globalData._url + model.url;
      }
    }

    //get参数拼接
    if (model.method == "get" && model.data !== undefined) {
      for (let k in model.data) {
        if (model.data[k].toString() !== '') {
          model.url = model.url + "&" + k + "=" + model.data[k];
        }
      }
      model.data = '';
    }

    //返回Promise对象
    return new Promise(
      function (resolve) {
        var token = wx.getStorageSync('token');
        var openid = wx.getStorageSync('openid');
        wx.request({
          method: model.method,
          url: model.url,
          header: {
            'token': token, // 默认值
            'client': that.globalData.client,//终端
            'company': that.globalData.company_id,//公司ID
            'boss-company': that.globalData.boss_company_id,//BOSS公司ID
            'role': that.globalData.role,//角色
            'openid': openid,

          },
          data: model.data,
          success: (resolve) => {
            if (util.isExitsVariable(model.load)) {
              wx.hideLoading();
            }
            if (resolve.data.code == -1005 || resolve.data.code == -1004) {
              console.log('*************************');
              that.redirectLogin();
              return false;
            }
            if(resolve.data.code==-1006){
              that.redirectLogin(resolve.data.message);
              return false;
            }

            model.success(resolve);

          },
          fail: (e) => {
            console.log(">>>>>>>>>>network error");
            that.showToast(JSON.stringify(e));          }
        })
      }
    )
  },
<<<<<<< HEAD
  globalData: {
    userInfo: null,
    _network_path: 'https://qn.youheone.com/cloud_engineer_weapp_image/company_huaxin/',
    _socket_url: 'wss://socket.youheone.com',
      // _url: 'https://yh.cqthesis.cn/',
      // boss_url: 'https://test.cqthesis.cn/',
      // crm_url: 'http://crm.cqthesis.cn/',
      //wx109200d9d5977713
    // _url: 'https://api.cqthesis.cn/',
    // boss_url: 'https://boss.cqthesis.cn/',
    
   _url: 'https://rqcrm.youheone.com/',
   boss_url: 'https://boss.youheone.com/',
   crm_url: 'https://yho.rqcrm.com/',
  //wx47014ae70582030d
    company_id:11,//origin 3
    client:1,//终端1微信 2支付宝
    role: 5,//角色 端1总后台 2运营 3行政 4用户 5工程
=======
  globalData: {
    userInfo: null,
    _network_path: 'https://api.itlantech.com//weapp/engineer/',
    _socket_url: 'wss://socket.youheone.com',
    _url: 'https://api.itlantech.com/',
    boss_url: 'https://boss.itlantech.com/',
    crm_url: 'http://crm.cqthesis.cn/',
    //wx109200d9d5977713
    // _url: 'https://api.cqthesis.cn/',
    // boss_url: 'https://boss.cqthesis.cn/',

    //  _url: 'https://rqcrm.youheone.com/',
    //  boss_url: 'https://boss.youheone.com/',
    //  crm_url: 'https://yho.rqcrm.com/',
    //wx47014ae70582030d
    company_id:1,
    boss_company_id:11,
    client:1,//终端1微信 2支付宝
    role: 5,//角色 端1总后台 2运营 3行政 4用户 5工程
>>>>>>> dev_glory
  },
  //弹窗MODEL
  showModal(title = "提示", content = "", success = function () { }, cancel=function(){}) {
    wx.showModal({
      title: title,
      content: content,
      showCancel: false,
      success: function (res) {
        if (res.confirm) {
          success();
        } else if (res.cancel) {
          cancel();
        } else if (!res.confirm && !res.cancel){
          cancel();
        }
      }
    })
  },
  //弹窗toast
  showToast(title = "", icon = "none", duration = 1500, complete = function () { }) {
    wx.showToast({
      title: title,
      icon: icon,
      duration: duration,
      complete: function (res) {
        complete();
      }
    })
    return false;
  },
  // 检测form表单
  checkForm(name, vlaue, msg) {
    if (name != vlaue) {
      return false;
    } else {
      this.showToast(msg);
      return true;
    }
  },
  /**
 * 系统信息
 */
  systemInfo: null,//系统信息
})
